package br.com.jk.cont.caixa;

import br.com.jk.cont.caixa.reports.CaixaReport;
import br.com.jk.cont.planocontas.PlanoContas;
import br.com.jk.cont.planocontas.PlanoContasDao;
import br.com.jk.cont.planocontas.PlanoContasJDialog;
import br.com.jk.cont.planocontas.PlanoContasRn;
import br.com.jk.empresa.Empresa;
import br.com.jk.empresa.EmpresaJDialog;
import br.com.jk.empresa.EmpresaRn;
import br.com.jk.financeiro.contaBanco.ContaBanco;
import br.com.jk.financeiro.contaBanco.ContaBancoJDialog;
import br.com.jk.financeiro.contaBanco.ContaBancoRn;
import br.com.jk.master.Master;
import br.com.jk.master.MasterSt;
import br.com.jk.usuario.jtable.UsuarioJTableUtil;
import br.com.jk.util.RNException;
import br.com.jk.util.Util;
import br.com.jk.util.parametro.ParametroData;
import br.com.jk.util.parametro.ParametroDataDialog;
import br.com.jk.util.parametro.ParametroEmpresa;
import br.com.jk.util.parametro.ParametroEmpresaDialog;
import br.com.jk.util.pesquisa.Pesquisa;
import br.com.jk.util.pesquisa.PesquisaJDialog;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.math.BigDecimal;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

/**
 *
 * @author camilo
 */
public class CaixaJDialog extends javax.swing.JDialog {

  private static CaixaJDialog dialog;
  private static final long serialVersionUID = 1L;
  // Model da tabela
  CaixaTableModel caixaTm = new CaixaTableModel();
  CaixaRn rn = new CaixaRn();
  List<Caixa> lstForn;
//  atributos utilizados nas pesquisas externas
  private JTextField idPesquisa;
  private JTextField razaoPesquisa;
  private boolean modoConsultaExt;
  private boolean modoConsulta;
  private static ParametroData parData = new ParametroData();
  private static ParametroEmpresa parEmp = new ParametroEmpresa();
  private static Pesquisa pesquisa = new Pesquisa();
  private double fator;
  private BigDecimal saldoIn;
  private BigDecimal saldoFin;
  private boolean contabanco;

  public static CaixaJDialog getInstance(java.awt.Frame parent, boolean modal) {
    if (dialog == null) {
      new ParametroEmpresaDialog(null, true, parEmp).setVisible(true);

      new ParametroDataDialog(null, true, true, parData).setVisible(true);

      dialog = new CaixaJDialog(parent, modal);
      dialog.setTitle(dialog.getTitle() + " - " + parEmp.getEmpresa().getFantasia() + " - De "
              + Util.formatData(parData.getDataInicial()) + " até "
              + Util.formatData(parData.getDataFinal()));
    }
    return dialog;
  }

  public static CaixaJDialog getInstance(java.awt.Frame parent, boolean modal, JTextField id, JTextField razao) {
    if (dialog == null) {
      dialog = new CaixaJDialog(parent, modal, id, razao);
    }
    return dialog;
  }

  /**
   * Creates new form FornecedorJDialog
   */
  private CaixaJDialog(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    init();
    criaModel();

    setLocationRelativeTo(null);
    listar();
    jlFiltro.setVisible(false);
  }

  private CaixaJDialog(java.awt.Frame parent, boolean modal, JTextField id, JTextField razao) {
    super(parent, modal);
    this.idPesquisa = id;
    this.razaoPesquisa = razao;
    this.modoConsultaExt = true;

    initComponents();
    criaModel();

    setLocationRelativeTo(null);
    listar();
    jlFiltro.setVisible(false);
  }

  private void criaModel() {
    jtCaixa.setModel(caixaTm);

    caixaTm.sorter(jtCaixa, caixaTm);

    UsuarioJTableUtil.alteraJTable(caixaTm, jtCaixa, "jtCaixa", Master.usuarioLogado);
  }

  private void init() {
    this.setSaldoInicial();
    this.setSaldoFinal();
  }

  /**
   * This method is called from within the constructor to initialize the form. WARNING: Do NOT
   * modify this code. The content of this method is always regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {
    java.awt.GridBagConstraints gridBagConstraints;

    jpmReport = new javax.swing.JPopupMenu();
    jmiMovAnalitico = new javax.swing.JMenuItem();
    JtbMaster = new javax.swing.JToolBar();
    JbNovo = new javax.swing.JButton();
    JbSalvar = new javax.swing.JButton();
    JbEditar = new javax.swing.JButton();
    JbCancelar = new javax.swing.JButton();
    JbExcluir = new javax.swing.JButton();
    JbBuscar = new javax.swing.JButton();
    JbRelatorio = new javax.swing.JButton();
    jSeparator1 = new javax.swing.JToolBar.Separator();
    JbRefresh = new javax.swing.JButton();
    jlFiltro = new javax.swing.JLabel();
    jSeparator2 = new javax.swing.JToolBar.Separator();
    jbJTable = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    jtCaixa = new javax.swing.JTable();
    jpDados = new javax.swing.JPanel();
    jlEmpresa = new javax.swing.JLabel();
    jtfIdEmpresa = new javax.swing.JTextField();
    jtfEmpresa = new javax.swing.JTextField();
    jlPlano = new javax.swing.JLabel();
    jtfCodPlano = new javax.swing.JTextField();
    jtfPlano = new javax.swing.JTextField();
    jlId = new javax.swing.JLabel();
    jtfId = new javax.swing.JTextField();
    jlIdImp = new javax.swing.JLabel();
    jtfIdImp = new javax.swing.JTextField();
    jlData = new javax.swing.JLabel();
    jftfData = new javax.swing.JFormattedTextField();
    jlNum = new javax.swing.JLabel();
    jtfNum = new javax.swing.JTextField();
    jlValor = new javax.swing.JLabel();
    jtfValor = new javax.swing.JTextField();
    jlConta = new javax.swing.JLabel();
    jtfIdConta = new javax.swing.JTextField();
    jtfConta = new javax.swing.JTextField();
    jlObservacao = new javax.swing.JLabel();
    jspObservacao = new javax.swing.JScrollPane();
    jtaObservacao = new javax.swing.JTextArea();
    jlSaldoInicial = new javax.swing.JLabel();
    jlValorSaldoInicial = new javax.swing.JLabel();
    jlSaldoFinal = new javax.swing.JLabel();
    jlValorSaldoFinal = new javax.swing.JLabel();

    jpmReport.setLightWeightPopupEnabled(false);

    jmiMovAnalitico.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jmiMovAnalitico.setText("Movimento Analítico");
    jmiMovAnalitico.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jmiMovAnaliticoActionPerformed(evt);
      }
    });
    jpmReport.add(jmiMovAnalitico);

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Gerenciamento do Caixa Contábil");
    addWindowListener(new java.awt.event.WindowAdapter() {
      public void windowClosed(java.awt.event.WindowEvent evt) {
        formWindowClosed(evt);
      }
    });

    JtbMaster.setOrientation(javax.swing.SwingConstants.VERTICAL);
    JtbMaster.setRollover(true);

    JbNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-new.png"))); // NOI18N
    JbNovo.setToolTipText("Novo Registro");
    JbNovo.setFocusable(false);
    JbNovo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbNovo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbNovo.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbNovoActionPerformed(evt);
      }
    });
    JtbMaster.add(JbNovo);
    JbNovo.setBackground(new Color(0,0,0,0));

    JbSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-save-hd.png"))); // NOI18N
    JbSalvar.setToolTipText("Salvar Registro");
    JbSalvar.setEnabled(false);
    JbSalvar.setFocusable(false);
    JbSalvar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbSalvar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbSalvar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbSalvarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbSalvar);

    JbEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-edit.png"))); // NOI18N
    JbEditar.setToolTipText("Alterar registro");
    JbEditar.setEnabled(false);
    JbEditar.setFocusable(false);
    JbEditar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbEditar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbEditar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbEditarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbEditar);

    JbCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/dialog-cancel.png"))); // NOI18N
    JbCancelar.setToolTipText("Cancelar");
    JbCancelar.setEnabled(false);
    JbCancelar.setFocusable(false);
    JbCancelar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbCancelar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbCancelar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbCancelarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbCancelar);

    JbExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/archive-remove.png"))); // NOI18N
    JbExcluir.setToolTipText("Excluir");
    JbExcluir.setEnabled(false);
    JbExcluir.setFocusable(false);
    JbExcluir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbExcluir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbExcluir.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbExcluirActionPerformed(evt);
      }
    });
    JtbMaster.add(JbExcluir);

    JbBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/edit-find.png"))); // NOI18N
    JbBuscar.setToolTipText("Buscar");
    JbBuscar.setEnabled(false);
    JbBuscar.setFocusable(false);
    JbBuscar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbBuscar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbBuscar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbBuscarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbBuscar);

    JbRelatorio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/report.png"))); // NOI18N
    JbRelatorio.setToolTipText("Relatórios");
    JbRelatorio.setFocusable(false);
    JbRelatorio.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbRelatorio.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbRelatorio.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbRelatorioActionPerformed(evt);
      }
    });
    JtbMaster.add(JbRelatorio);
    JtbMaster.add(jSeparator1);

    JbRefresh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/view-refresh.png"))); // NOI18N
    JbRefresh.setToolTipText("Atualizar registros da lista");
    JbRefresh.setFocusable(false);
    JbRefresh.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbRefresh.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbRefresh.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbRefreshActionPerformed(evt);
      }
    });
    JtbMaster.add(JbRefresh);

    jlFiltro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/task-attempt.png"))); // NOI18N
    JtbMaster.add(jlFiltro);
    JtbMaster.add(jSeparator2);

    jbJTable.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/view-form-table.png"))); // NOI18N
    jbJTable.setToolTipText("Grava as informações da JTable");
    jbJTable.setFocusable(false);
    jbJTable.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    jbJTable.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    jbJTable.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbJTableActionPerformed(evt);
      }
    });
    JtbMaster.add(jbJTable);

    /*jtCaixa.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
      public void valueChanged(ListSelectionEvent evt){
        if (evt.getValueIsAdjusting()){
          return;
        }
        int selected = jtCaixa.getSelectedRow();
        fControl.selecionado();
      }
    });

    jtCaixa.getColumnModel().getSelectionModel().addListSelectionListener(new ListSelectionListener(){
      public void valueChanged(ListSelectionEvent evt){
        if (evt.getValueIsAdjusting()){
          return;
        }
        int selected = jtCaixa.getSelectedColumn();
        fControl.selecionado();
      }
    });*/
    jtCaixa.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
    jtCaixa.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseClicked(java.awt.event.MouseEvent evt) {
        jtCaixaMouseClicked(evt);
      }
    });
    jtCaixa.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtCaixaKeyPressed(evt);
      }
      public void keyReleased(java.awt.event.KeyEvent evt) {
        jtCaixaKeyReleased(evt);
      }
    });
    jScrollPane1.setViewportView(jtCaixa);

    jpDados.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder(""), "Dados"));
    java.awt.GridBagLayout jpDadosLayout = new java.awt.GridBagLayout();
    jpDadosLayout.columnWidths = new int[] {100, 10, 100, 10, 100, 10, 100, 10, 100, 10, 100};
    jpDados.setLayout(jpDadosLayout);

    jlEmpresa.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jlEmpresa.setText("Empresa");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jlEmpresa, gridBagConstraints);

    jtfIdEmpresa.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfIdEmpresa.setEnabled(false);
    jtfIdEmpresa.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfIdEmpresaKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints.ipadx = 27;
    jpDados.add(jtfIdEmpresa, gridBagConstraints);

    jtfEmpresa.setEditable(false);
    jtfEmpresa.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfEmpresa.setEnabled(false);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.gridwidth = 3;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfEmpresa, gridBagConstraints);

    jlPlano.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jlPlano.setText("Plano Contas");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 6;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
    jpDados.add(jlPlano, gridBagConstraints);

    jtfCodPlano.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfCodPlano.setEnabled(false);
    jtfCodPlano.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfCodPlanoKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 6;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    jpDados.add(jtfCodPlano, gridBagConstraints);

    jtfPlano.setEditable(false);
    jtfPlano.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfPlano.setEnabled(false);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 8;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.gridwidth = 3;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    jpDados.add(jtfPlano, gridBagConstraints);

    jlId.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jlId.setText("Id");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jlId, gridBagConstraints);

    jtfId.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfId.setEnabled(false);
    jtfId.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfIdKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfId, gridBagConstraints);

    jlIdImp.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jlIdImp.setText("Id Imp");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jlIdImp, gridBagConstraints);

    jtfIdImp.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfIdImp.setEnabled(false);
    jtfIdImp.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusLost(java.awt.event.FocusEvent evt) {
        jtfIdImpFocusLost(evt);
      }
    });
    jtfIdImp.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfIdImpKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfIdImp, gridBagConstraints);

    jlData.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jlData.setText("Data");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 4;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jlData, gridBagConstraints);

    jftfData.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter()));
    jftfData.setHorizontalAlignment(javax.swing.JTextField.CENTER);
    jftfData.setEnabled(false);
    jftfData.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jftfData.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusLost(java.awt.event.FocusEvent evt) {
        jftfDataFocusLost(evt);
      }
    });
    jftfData.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jftfDataKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 4;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    jpDados.add(jftfData, gridBagConstraints);

    jlNum.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jlNum.setText("Nº");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 6;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jlNum, gridBagConstraints);

    jtfNum.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfNum.setEnabled(false);
    jtfNum.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfNumKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 6;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfNum, gridBagConstraints);

    jlValor.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jlValor.setText("Valor");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 8;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jlValor, gridBagConstraints);

    jtfValor.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfValor.setEnabled(false);
    jtfValor.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusLost(java.awt.event.FocusEvent evt) {
        jtfValorFocusLost(evt);
      }
    });
    jtfValor.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfValorKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 8;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfValor, gridBagConstraints);

    jlConta.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jlConta.setText("C/C");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 4;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
    jpDados.add(jlConta, gridBagConstraints);

    jtfIdConta.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfIdConta.setEnabled(false);
    jtfIdConta.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfIdContaKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 5;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_START;
    jpDados.add(jtfIdConta, gridBagConstraints);

    jtfConta.setEditable(false);
    jtfConta.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfConta.setEnabled(false);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 5;
    gridBagConstraints.gridwidth = 3;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_START;
    jpDados.add(jtfConta, gridBagConstraints);

    jlObservacao.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jlObservacao.setText("Observação");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 6;
    gridBagConstraints.gridy = 4;
    jpDados.add(jlObservacao, gridBagConstraints);

    jtaObservacao.setColumns(20);
    jtaObservacao.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtaObservacao.setRows(5);
    jtaObservacao.setEnabled(false);
    jspObservacao.setViewportView(jtaObservacao);

    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 6;
    gridBagConstraints.gridy = 5;
    gridBagConstraints.gridwidth = 5;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jspObservacao, gridBagConstraints);

    jlSaldoInicial.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N
    jlSaldoInicial.setText("Saldo Inicial");

    jlValorSaldoInicial.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N
    jlValorSaldoInicial.setText("R$");
    jlValorSaldoInicial.setOpaque(true);

    jlSaldoFinal.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N
    jlSaldoFinal.setText("Saldo Final");

    jlValorSaldoFinal.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N
    jlValorSaldoFinal.setText("R$");
    jlValorSaldoFinal.setOpaque(true);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addComponent(JtbMaster, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addGap(3, 3, 3)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jpDados, javax.swing.GroupLayout.DEFAULT_SIZE, 989, Short.MAX_VALUE)
          .addGroup(layout.createSequentialGroup()
            .addComponent(jlSaldoInicial)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jlValorSaldoInicial)
            .addGap(108, 108, 108)
            .addComponent(jlSaldoFinal)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jlValorSaldoFinal)
            .addGap(0, 0, Short.MAX_VALUE))
          .addComponent(jScrollPane1)))
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jlSaldoInicial)
          .addComponent(jlValorSaldoInicial)
          .addComponent(jlSaldoFinal)
          .addComponent(jlValorSaldoFinal))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jpDados, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addGap(3, 3, 3))
      .addComponent(JtbMaster, javax.swing.GroupLayout.DEFAULT_SIZE, 586, Short.MAX_VALUE)
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void JbNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbNovoActionPerformed
    novo();
  }//GEN-LAST:event_JbNovoActionPerformed

  private void JbSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbSalvarActionPerformed
    salvar();
  }//GEN-LAST:event_JbSalvarActionPerformed

  private void JbEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbEditarActionPerformed
    editar();
    MasterSt.setJlStatusMessage("Sistema pronto para executar a alteração do registro.");
  }//GEN-LAST:event_JbEditarActionPerformed

  private void JbCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbCancelarActionPerformed
    cancelar();
  }//GEN-LAST:event_JbCancelarActionPerformed

  private void JbExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbExcluirActionPerformed
    excluir();
  }//GEN-LAST:event_JbExcluirActionPerformed

  private void JbBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbBuscarActionPerformed
    pesquisar();
  }//GEN-LAST:event_JbBuscarActionPerformed

  private void JbRelatorioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbRelatorioActionPerformed
    jpmReport.setBackground(new Color(242, 241, 240, 150));
    jmiMovAnalitico.setBackground(new Color(255, 0, 0, 150));
    jpmReport.show(JbRelatorio, 5, 20);
  }//GEN-LAST:event_JbRelatorioActionPerformed

  private void JbRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbRefreshActionPerformed
    this.listar();
    jlFiltro.setVisible(false);
    JbBuscar.setEnabled(false);
    MasterSt.setJlStatusMessage("Atualizado");
  }//GEN-LAST:event_JbRefreshActionPerformed

  private void jtCaixaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtCaixaMouseClicked
    if (caixaTm.getRowCount() > 0 && (jtfId.getText() != null)) {
      habilitaJb(true, false, true, false, true);
      habilitaJtf(false);
      limpar();
      selecionado();
    }
  }//GEN-LAST:event_jtCaixaMouseClicked

  private void jtfIdKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfIdKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfNum.requestFocus();
    }
  }//GEN-LAST:event_jtfIdKeyPressed

  private void jtfNumKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfNumKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfValor.requestFocus();
    }
  }//GEN-LAST:event_jtfNumKeyPressed

  private void jtfIdImpKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfIdImpKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jftfData.requestFocus();
    }
  }//GEN-LAST:event_jtfIdImpKeyPressed

  private void jtfValorKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfValorKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (contabanco) {
        jtfIdConta.setEnabled(true);
        jtfIdConta.requestFocus();
      } else {
        jtaObservacao.requestFocus();
      }
    }
  }//GEN-LAST:event_jtfValorKeyPressed

  private void jtfIdEmpresaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfIdEmpresaKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (jtfIdEmpresa.getText().isEmpty()) {
        selecionaEmpresa();
        jtfCodPlano.requestFocus();
      } else {
        Empresa empresa = this.carregaEmpresa(Integer.parseInt(jtfIdEmpresa.getText()));
        jtfIdEmpresa.setText(String.valueOf(empresa.getId()));
        jtfEmpresa.setText(empresa.getRazao());
        jtfCodPlano.requestFocus();
      }
    } else if (evt.getKeyCode() == KeyEvent.VK_F12) {
      selecionaEmpresa();
    }
  }//GEN-LAST:event_jtfIdEmpresaKeyPressed

  private void jtCaixaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtCaixaKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_SPACE) {
      if (JbBuscar.isEnabled()) {
        pesquisar();
      }
    } else if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (modoConsultaExt) {
        selecionaRegistro();
      }
    }
  }//GEN-LAST:event_jtCaixaKeyPressed

  private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
    MasterSt.setJlStatusNull();
    dialog = null;
  }//GEN-LAST:event_formWindowClosed

  private void jtfIdImpFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfIdImpFocusLost
    if (jtfIdImp.getText().isEmpty()) {
      jtfIdImp.setText("0");
    }
  }//GEN-LAST:event_jtfIdImpFocusLost

  private void jbJTableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbJTableActionPerformed
    getLarguraJtBanco();
    MasterSt.setJlStatusMessage("As dimensões e posições das colunas da tabela foram salvas.");
  }//GEN-LAST:event_jbJTableActionPerformed

  private void jtfCodPlanoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfCodPlanoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (jtfCodPlano.getText().isEmpty()) {
        selecionaPlano();
        jtfIdImp.requestFocus();
      } else {
        try {
          PlanoContas plano = this.carregaPlano(jtfCodPlano.getText());
          jtfCodPlano.setText(String.valueOf(plano.getCod()));
          jtfPlano.setText(plano.getDescricao());
          jtfIdImp.requestFocus();
        } catch (RNException e) {
          Util.msgAdv(e);
          jtfCodPlano.requestFocus();
        }
      }
    } else if (evt.getKeyCode() == KeyEvent.VK_F12) {
      selecionaPlano();
    }
  }//GEN-LAST:event_jtfCodPlanoKeyPressed

  private void jtfIdContaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfIdContaKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (jtfIdConta.getText().isEmpty() || jtfIdConta.getText().equals("0")) {
        selecionaConta();
        jtaObservacao.requestFocus();
      } else {
        ContaBanco conta = this.carregaContaBanco(Integer.parseInt(jtfIdConta.getText()));
        jtfIdConta.setText(String.valueOf(conta.getId()));
        jtfConta.setText(conta.getDescricao());
        jtaObservacao.requestFocus();
      }
    } else if (evt.getKeyCode() == KeyEvent.VK_F12) {
      selecionaConta();
    }
  }//GEN-LAST:event_jtfIdContaKeyPressed

  private void jftfDataKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jftfDataKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfNum.requestFocus();
    }
  }//GEN-LAST:event_jftfDataKeyPressed

  private void jftfDataFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jftfDataFocusLost
    if (jftfData.getText().isEmpty()) {
      Util.msgAdv("O campo \"Data\" não pode ser vazio.");
      jftfData.requestFocus();
    }
  }//GEN-LAST:event_jftfDataFocusLost

  private void jtfValorFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfValorFocusLost
    if (jtfValor.getText().isEmpty()) {
      Util.msgAdv("O campo \"Valor\" não pode ser vazio.");
    } else {
      Double valor = Double.parseDouble(jtfValor.getText());

//      Verifica se o valor está diferente do fator estabelecido pelo plano de contas do lançamento
//      Exemplo: Se a conta for Natureza = S e o valor do lançamento estiver positivo ele converte, 
//      caso contrário não será realizada nenhuma alteração.
      if (valor < 0 && this.fator > 0) {
        valor = valor * this.fator;
      } else if (valor > 0 && this.fator < 0) {
        valor = valor * this.fator;
      }
      jtfValor.setText(valor.toString());
    }
  }//GEN-LAST:event_jtfValorFocusLost

  private void jtCaixaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtCaixaKeyReleased
    if (evt.getKeyCode() == KeyEvent.VK_UP
            || evt.getKeyCode() == KeyEvent.VK_DOWN
            || evt.getKeyCode() == KeyEvent.VK_LEFT
            || evt.getKeyCode() == KeyEvent.VK_RIGHT) {
      selecionado();
    }
  }//GEN-LAST:event_jtCaixaKeyReleased

  private void jmiMovAnaliticoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmiMovAnaliticoActionPerformed
    MasterSt.setJpbIndeterminate(true);
    MasterSt.setJlStatusMessage("Aguarde, o sistema está gerando o relatório...");

    new Thread(new Runnable() {
      @Override
      public void run() {
        CaixaReport report = new CaixaReport();
        int resposta = JOptionPane.showConfirmDialog(null,
                "O sistema solicitou parâmetros na tela de gerenciamento do movimento contábil. \n"
                + "Deseja usar os mesmos parâmetros?\n\nParâmetros carregados em memória:\n"
                + "Empresa: " + parEmp.getEmpresa().getId() + " - " + parEmp.getEmpresa().getFantasia()
                + "\nPeríodo: De " + Util.formatData(parData.getDataInicial())
                + " até " + Util.formatData(parData.getDataFinal()),
                "Parâmetros",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE);

        if (resposta == JOptionPane.YES_OPTION) {
          report.geraReportMovAnalitico(parEmp, parData, saldoIn);
        } else if (resposta == JOptionPane.NO_OPTION) {
          CaixaRn caixaRn = new CaixaRn();
          ParametroEmpresa parEmpReport = new ParametroEmpresa();
          ParametroData parDataReport = new ParametroData();

          new ParametroEmpresaDialog(null, true, parEmpReport).setVisible(true);
          new ParametroDataDialog(null, true, true, parDataReport).setVisible(true);
          BigDecimal saldo = caixaRn.getSaldoInicial(parEmpReport.getEmpresa(), parDataReport.getDataInicial());

          report.geraReportMovAnalitico(parEmpReport, parDataReport, saldo);
        }
      }
    }).start();
  }//GEN-LAST:event_jmiMovAnaliticoActionPerformed

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          javax.swing.UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(CaixaJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the dialog */
    java.awt.EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        CaixaJDialog dialog = new CaixaJDialog(new javax.swing.JFrame(), true);
        dialog.addWindowListener(new java.awt.event.WindowAdapter() {
          @Override
          public void windowClosing(java.awt.event.WindowEvent e) {
            System.exit(0);
          }
        });
        dialog.setVisible(true);
      }
    });
  }
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton JbBuscar;
  private javax.swing.JButton JbCancelar;
  private javax.swing.JButton JbEditar;
  private javax.swing.JButton JbExcluir;
  private javax.swing.JButton JbNovo;
  private javax.swing.JButton JbRefresh;
  private javax.swing.JButton JbRelatorio;
  private javax.swing.JButton JbSalvar;
  private javax.swing.JToolBar JtbMaster;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JToolBar.Separator jSeparator1;
  private javax.swing.JToolBar.Separator jSeparator2;
  private javax.swing.JButton jbJTable;
  private javax.swing.JFormattedTextField jftfData;
  private javax.swing.JLabel jlConta;
  private javax.swing.JLabel jlData;
  private javax.swing.JLabel jlEmpresa;
  private javax.swing.JLabel jlFiltro;
  private javax.swing.JLabel jlId;
  private javax.swing.JLabel jlIdImp;
  private javax.swing.JLabel jlNum;
  private javax.swing.JLabel jlObservacao;
  private javax.swing.JLabel jlPlano;
  private javax.swing.JLabel jlSaldoFinal;
  private javax.swing.JLabel jlSaldoInicial;
  private javax.swing.JLabel jlValor;
  private javax.swing.JLabel jlValorSaldoFinal;
  private javax.swing.JLabel jlValorSaldoInicial;
  private javax.swing.JMenuItem jmiMovAnalitico;
  private javax.swing.JPanel jpDados;
  private javax.swing.JPopupMenu jpmReport;
  private javax.swing.JScrollPane jspObservacao;
  private javax.swing.JTable jtCaixa;
  private javax.swing.JTextArea jtaObservacao;
  private javax.swing.JTextField jtfCodPlano;
  private javax.swing.JTextField jtfConta;
  private javax.swing.JTextField jtfEmpresa;
  private javax.swing.JTextField jtfId;
  private javax.swing.JTextField jtfIdConta;
  private javax.swing.JTextField jtfIdEmpresa;
  private javax.swing.JTextField jtfIdImp;
  private javax.swing.JTextField jtfNum;
  private javax.swing.JTextField jtfPlano;
  private javax.swing.JTextField jtfValor;
  // End of variables declaration//GEN-END:variables

  public void novo() {
    limpar();
    habilitaJb(false, true, false, true, false);
    habilitaJtf(true);
    jtfIdEmpresa.requestFocus();
    MasterSt.setJlStatusMessage("Sistema pronto para criar um novo registro.");
  }

  private void getLarguraJtBanco() {
    MasterSt.setJlStatusMessage("Obtendo configurações das dimensões e posição das colunas para a tabela");
    UsuarioJTableUtil.setUsuarioJTable(caixaTm, jtCaixa, "jtCaixa", Master.usuarioLogado);
  }

  private void selecionaEmpresa() {
    EmpresaJDialog.getInstance(null, true, jtfIdEmpresa, jtfEmpresa).setVisible(true);
  }

  private void selecionaPlano() {
    PlanoContasJDialog.getInstance(null, true, jtfCodPlano, jtfPlano).setVisible(true);
  }

  private ContaBanco selecionaConta() {
    ContaBanco cnt = new ContaBanco();
    ContaBancoJDialog.getInstance(null, true, cnt).setVisible(true);
    return cnt;
  }

  public void selecionado() {
    int linha = jtCaixa.getSelectedRow();//grava a linha selecionada
    int linhaSel = jtCaixa.convertRowIndexToModel(linha);

    if (linhaSel >= 0) { // executa o procedimento se o JTable não estiver vazio
      int colunaSel = jtCaixa.getSelectedColumn(); //grava a coluna selecionada
      boolean pesq = rn.setEnabledPesquisa(colunaSel); // Verifica as colunas que serão habilitadas para pesquisa

      jtfIdEmpresa.setText(caixaTm.getValueAt(linhaSel, CaixaTableModel.COLUNA_COD_ID_EMPRESA).toString());
      jtfEmpresa.setText(caixaTm.getValueAt(linhaSel, CaixaTableModel.COLUNA_COD_EMPRESA).toString());
      jtfCodPlano.setText(caixaTm.getValueAt(linhaSel, CaixaTableModel.COLUNA_COD_ID_PLANO_CONTAS).toString());
      jtfPlano.setText(caixaTm.getValueAt(linhaSel, CaixaTableModel.COLUNA_COD_PLANO_CONTAS).toString());
      jtfId.setText(caixaTm.getValueAt(linhaSel, CaixaTableModel.COLUNA_COD_ID).toString());
      jtfValor.setText(caixaTm.getValueAt(linhaSel, CaixaTableModel.COLUNA_COD_VALOR).toString());
      jtfIdImp.setText(caixaTm.getValueAt(linhaSel, CaixaTableModel.COLUNA_COD_ID_IMP).toString());
      jtfNum.setText(caixaTm.getValueAt(linhaSel, CaixaTableModel.COLUNA_COD_DOC).toString());
      jftfData.setText(Util.formatDataStoS(caixaTm.getValueAt(linhaSel, CaixaTableModel.COLUNA_COD_DATA).toString()));
      jtfIdConta.setText(caixaTm.getValueAt(linhaSel, CaixaTableModel.COLUNA_COD_ID_CONTA_BANCO).toString());
      jtfConta.setText(caixaTm.getValueAt(linhaSel, CaixaTableModel.COLUNA_COD_CONTA_BANCO).toString());
      jtaObservacao.setText(caixaTm.getValueAt(linhaSel, CaixaTableModel.COLUNA_COD_OBSERVACAO).toString());

      modoConsulta = pesq;
      JbBuscar.setEnabled(pesq);
    }
  }

  public Caixa criaObjeto() {
    Caixa caixa = new Caixa();

    try {
      caixa.setEmpresa(carregaEmpresa(Integer.parseInt(jtfIdEmpresa.getText())));
      caixa.setPlanoContas(carregaPlano(jtfCodPlano.getText()));
      caixa.setIdImp(Integer.parseInt(jtfIdImp.getText()));
      caixa.setData(Util.formatDataSToD(jftfData.getText()));
      caixa.setDoc(jtfNum.getText());
      caixa.setValor(new BigDecimal(jtfValor.getText()));
      caixa.setObservacao(jtaObservacao.getText());

      if (!jtfIdConta.getText().isEmpty()) {
        caixa.setContaBanco(carregaContaBanco(Integer.parseInt(jtfIdConta.getText())));
      } else {
        caixa.setContaBanco(carregaContaBanco(0));
      }

      if (!jtfId.getText().isEmpty()) {
        caixa.setId(Integer.parseInt(jtfId.getText()));
      }
    } catch (RNException e) {
      Util.msgAdv(e, "Erro ao criar o objeto.");
    } catch (NumberFormatException e) {
      Util.msgErro(e, "Erro na formatação dos números");
    }

    return caixa;
  }

  private void salvar() {
    CaixaRn caixaRn = new CaixaRn();
    caixaRn.salvar(criaObjeto());
    listar();
    habilitaJb(true, false, false, false, false);
    habilitaJtf(false);
    limpar();
    MasterSt.setJlStatusMessage("Registro salvo.");
  }

  private void listar() {
    CaixaRn cxrn = new CaixaRn();
    setJtProdutoTm(cxrn.listar(parData, parEmp));
    this.setSaldoInicial();
    this.setSaldoFinal();
    limpar();
    MasterSt.setJlStatusMessage("Listagem de registros atualizada.");
  }

  private void limpar() {
    jtfNum.setText(null);
    jtaObservacao.setText(null);
    jtfIdImp.setText(null);
    jtfEmpresa.setText(null);
    jtfId.setText(null);
    jtfIdEmpresa.setText(null);
    jtfCodPlano.setText(null);
    jtfPlano.setText(null);
    jftfData.setText(null);
    jtfConta.setText(null);
    jtfIdConta.setText(null);
    jtfValor.setText(null);
    JbBuscar.setEnabled(false);
  }

  public void setJtProdutoTm(List<Caixa> ct) {
    removeAllJtable();
    if (!ct.isEmpty()) {
      caixaTm.adicionaLista(ct);
    }
  }

  public void setJtProdutoTm(Caixa ct) {
    removeAllJtable();
    if (ct != null) {
      caixaTm.adiciona(ct);
    }
  }

  private void removeAllJtable() {
    while (caixaTm.getRowCount() > 0) {
      caixaTm.remove(0);
    }
  }

  /**
   * Determina quais os botões da barra de ferramentas ficará ativo
   *
   * @param novo
   * @param salvar
   * @param editar
   * @param cancelar
   * @param excluir
   */
  public void habilitaJb(Boolean novo, Boolean salvar, Boolean editar, Boolean cancelar,
          Boolean excluir) {
    JbNovo.setEnabled(novo);
    JbSalvar.setEnabled(salvar);
    JbEditar.setEnabled(editar);
    JbCancelar.setEnabled(cancelar);
    JbExcluir.setEnabled(excluir);
  }

  /**
   * Define se os JTextFields serão liberados para edição do usuário
   *
   * @param tf <b>True</b> - Habilitar; <b>False</b> - Desabilitar;
   */
  public void habilitaJtf(Boolean tf) {
    jtfIdImp.setEnabled(tf);
    jtfNum.setEnabled(tf);
    jtaObservacao.setEnabled(tf);
    jtfIdEmpresa.setEnabled(tf);
    jtfValor.setEnabled(tf);
    jtfCodPlano.setEnabled(tf);
    jftfData.setEnabled(tf);
    jtfIdConta.setEnabled(tf);
  }

  private void editar() {
    habilitaJb(false, true, false, true, false);
    habilitaJtf(true);
    jtfIdEmpresa.requestFocus();
  }

  private void excluir() {
    CaixaRn crn = new CaixaRn();
    crn.excluir(criaObjeto());
    listar();
    limpar();
  }

  private void cancelar() {
    limpar();
    habilitaJb(true, false, false, false, false);
    habilitaJtf(false);

    if (this.modoConsulta) {
      this.modoConsulta = false;
    } else {
      listar();
    }
  }

  private void selecionaRegistro() {
    int linha = jtCaixa.getSelectedRow();
    int linhaSel = jtCaixa.convertRowIndexToModel(linha);
    idPesquisa.setText(caixaTm.getValueAt(linhaSel, CaixaTableModel.COLUNA_COD_ID).toString());
    razaoPesquisa.setText(caixaTm.getValueAt(linhaSel, CaixaTableModel.COLUNA_COD_DOC).toString());
    modoConsultaExt = false;
    this.dispose();
  }

  private Empresa carregaEmpresa(int idEmp) {
    Empresa empresa = new Empresa();
    EmpresaRn empresaRn = new EmpresaRn();
    try {
      empresa = empresaRn.carregar(idEmp);
    } catch (RNException e) {
      Util.msgErro(e, "Erro ao consultar o cadastro de empresas");
    }
    return empresa;
  }

  private PlanoContas carregaPlano(String parseInt) throws RNException {
    PlanoContasRn planoRn = new PlanoContasRn();
    PlanoContas plano = planoRn.carregarCod(parseInt);

    switch (plano.getNatureza()) {
      case PlanoContasDao.NATUREZA_ENTRADA:
        this.fator = 1;
        break;
      case PlanoContasDao.NATUREZA_SAIDA:
        this.fator = -1;
        break;
    }
    System.out.println("Natureza = " + plano.getNatureza() + " fator = " + fator);

    if (plano.isTitulo()) {
      throw new RNException("Você não pode utilizar uma conta título para lançamentos.\n\n"
              + "Escolha uma nova conta.");
    }

    try {
      contabanco = plano.isContaBanco();
    } catch (NullPointerException e) {
      contabanco = false;
    }

    return plano;
  }

  private ContaBanco carregaContaBanco(int id) {
    ContaBancoRn crn = new ContaBancoRn();
    ContaBanco conta = crn.carregar(id);
    return conta;
  }

  private void setSaldoInicial() {
    CaixaRn caixaRn = new CaixaRn();
    try {
      saldoIn = caixaRn.getSaldoInicial(parEmp.getEmpresa(), parData.getDataInicial());
      jlValorSaldoInicial.setText("R$ " + saldoIn.toString());
    } catch (NullPointerException e) {
      Util.msgAdv(e, "Não foram encontrados lançamentos anteriores à data informada.\n\n"
              + "Será utilizado o valor R$ 0,00 para o saldo inicial.");
      saldoIn = new BigDecimal("0");
      jlValorSaldoInicial.setText("R$ " + saldoIn.toString());
    }

    if (saldoIn.compareTo(BigDecimal.ZERO) >= 0) {
      jlValorSaldoInicial.setBackground(Color.green);
    } else {
      jlValorSaldoInicial.setBackground(Color.red);
    }
  }

  private void setSaldoFinal() {
    CaixaRn caixaRn = new CaixaRn();
    saldoFin = caixaRn.getSaldoFinal(parEmp.getEmpresa(), parData.getDataFinal());
    jlValorSaldoFinal.setText("R$ " + saldoFin.toString());

    if (saldoFin.compareTo(BigDecimal.ZERO) >= 0) {
      jlValorSaldoFinal.setBackground(Color.green);
    } else {
      jlValorSaldoFinal.setBackground(Color.red);
    }
  }

  private void pesquisar() {
    PesquisaJDialog.getCriterio(caixaTm.getTipoPesquisa(jtCaixa.convertColumnIndexToView(jtCaixa.getSelectedColumn())));
    CaixaRn cxrn = new CaixaRn();
    cxrn.pesquisa(PesquisaJDialog.pesquisa);
//    CaixaJDialog.pesquisa = PesquisaJDialog.pesquisa;
  }
}
